package com.ruoyi.ruoyiqywechat.aliyunconfig;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.io.File;
import java.util.HashMap;
@Configuration
public class SpeechFlashRecognizerDemo {
    private String appkey;
    public String process(String fileName, String token,String format, int sampleRate) {
        /**
        * 设置HTTPS REST POST请求
        * 1.使用http协议
        * 2.语音识别服务域名：nls-gateway-cn-shanghai.aliyuncs.com
        * 3.语音识别接口请求路径：/stream/v1/FlashRecognizer
        * 4.设置必须请求参数：appkey、token、format、sample_rate
        */
        String url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/FlashRecognizer";
        String request = url;
        request = request + "?appkey=" + appkey;
        request = request + "&token=" + token;
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + sampleRate;

        System.out.println("Request: " + request);
        /**
        * 设置HTTPS头部字段
        *
        * 1.Content-Type：application/octet-stream
        */
        HashMap<String, String> headers = new HashMap<String, String>();
        /**
        * 发送HTTPS POST请求，返回服务端的响应。
        */
        long start = System.currentTimeMillis();
        String response;
        File audioFile = new File(fileName);

        System.out.println("=== 文件诊断信息 ===");
        System.out.println("输入路径: " + fileName);
        System.out.println("绝对路径: " + audioFile.getAbsolutePath());
        System.out.println("文件是否存在: " + audioFile.exists());
        System.out.println("是否是文件: " + audioFile.isFile());
        System.out.println("是否是目录: " + audioFile.isDirectory());
        System.out.println("文件大小: " + (audioFile.exists() ? audioFile.length() + " bytes" : "N/A"));
        System.out.println("可读: " + audioFile.canRead());
        System.out.println("可写: " + audioFile.canWrite());
        System.out.println("父目录: " + audioFile.getParent());
        System.out.println("文件名: " + audioFile.getName());
//        if (new File(audioFile.getAbsolutePath()).isFile()){
            System.out.println(" headers.put(\"Content-Type\", \"application/octet-stream\")");
            headers.put("Content-Type", "application/octet-stream");
            response = HttpUtil.sendPostFile(request, headers, audioFile.getAbsolutePath());
//        }else {
//            System.out.println(" headers.put(\"Content-Type\", \"application/text\")");
//            headers.put("Content-Type", "application/text");
//            response = HttpUtil.sendPostLink(request, headers, fileName);
//        }
        System.out.println("latency = " + (System.currentTimeMillis() - start) + " ms");
        if (response != null) {
            System.out.println("Response: " + response);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = null;
            StringBuilder stringBuilder = new StringBuilder();
            try {
                rootNode = mapper.readTree(response);
                JsonNode sentencesNode = rootNode.path("flash_result").path("sentences");
                for (JsonNode sentence : sentencesNode) {
                    String text = sentence.path("text").asText();
                    stringBuilder.append(text);
                }
                return stringBuilder.toString();
            } catch (JsonProcessingException e) {
                throw new RuntimeException("音频转文案识别不了!");
            }
        }
        else {
            System.err.println("识别失败!");
            throw new RuntimeException("识别失败!");
        }
    }
    public  String uploadfile(String fileName,String token,String appkey) {
        this.appkey = appkey;
        //String fileName = SpeechRecognizerRestfulDemo.class.getClassLoader().getResource("./nls-sample-16k.wav").getPath();
        // 重要：此处用一个本地文件来模拟发送实时流数据，实际使用时，您可以从某处实时采集或接收语音流并发送到ASR服务端。
//        String fileName = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";
        String format = "MP3";
        int sampleRate = 16000;
       return process(fileName,token, format, sampleRate);
    }
}
